/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.services;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.apps.datastore.dao.BookInformation;
import com.apps.datastore.dao.UniqueCourseObject;

public class UBCSectionDetailService {

	private static final int TOTAL = 0;
	private static final int REGISTERED = 1;
	private static final int GENERAL = 2;
	private static final int RESTRICTED = 3;
	
	private static final int TERM = 0;
	private static final int DAY = 1;
	private static final int START = 2;
	private static final int END = 3;
	private static final int BUILDING = 4;
	private static final int ROOM = 5;

	private  BufferedReader urlContent;
	private  long[] seatInformationArray;
	private  String[] courseInformation;
	private  List<BookInformation> bookList;

	public UBCSectionDetailService() {
		 seatInformationArray = new long[4];
		 courseInformation = new String[6];
		 bookList = new ArrayList<BookInformation>();
	}
	
	public int init(String dept, String course, String section){
		UniqueCourseObject uco = new UniqueCourseObject(dept.toUpperCase(),course,section);
		return initContent(uco);
	}

	public int initContent(UniqueCourseObject uco) {
		int out = -2;
		try {
			urlContent = getURLContentReader(uco.getDepartmentName(),
					uco.getCourseNumber(), uco.getSectionNumber());
			out = parseURLContent(urlContent);
		} catch (Exception e) {
			System.err.println("Could not establish connection");
		}
		return out;
	}

	public long getTotalSeats() {
		return seatInformationArray[TOTAL];
	}

	public long getRegistered() {
		return seatInformationArray[REGISTERED];
	}

	public long getGenSeatsRemain() {
		return seatInformationArray[GENERAL];
	}

	public long getRestrictSeatsRemain() {
		return seatInformationArray[RESTRICTED];
	}

	public String getTerm() {
		return courseInformation[TERM];
	}

	public String getDay() {
		return courseInformation[DAY];
	}

	public String getStartTime() {
		return courseInformation[START];
	}

	public String getEndTime() {
		return courseInformation[END];
	}

	public String getBuilding() {
		return courseInformation[BUILDING];
	}

	public String getRoom() {
		return courseInformation[ROOM];
	}
	
	public List<BookInformation> getBookList() {
		return bookList;
	}

	private BufferedReader getURLContentReader(String dept,
			String course, String section) throws Exception {
		String url = "https://courses.students.ubc.ca/cs/main?pname=subjarea&tname=subjareas&req=5&dept="
				+ dept + "&course=" + course + "&section=" + section;
		return new BufferedReader(new InputStreamReader(
				new URL(url).openStream()));
	}

	private int parseURLContent(BufferedReader br) throws IOException {
		String line = br.readLine();
		String result = "";
		boolean classInfoFoundFlag = false;
		boolean instructorInfoFoundFlag = false;
		boolean seatInfoFoundFlag = false;
		boolean bookInfoFoundFlag = false;
		while (line != null) {
//			if (line.contains("<td nowrap><b>Room</b></td>")) {
//				classInfoFoundFlag = true;
//				line = br.readLine();
//				boolean courseInfoLocatedFlag = false;
//				while (line != null && courseInfoLocatedFlag == false) {
//					if (line.contains("<td nowrap>")) {
//						for (int i = 0; i < 5; i++) {
//							if(line.contains("</td>"))
//								courseInformation[i] = line.substring(line.indexOf("<td nowrap>") + 11,line.indexOf("</td>")).trim().replaceAll("&nbsp;", "");
//							else
//								courseInformation[i] = line.substring(line.indexOf("<td nowrap>") + 11).trim().replaceAll("&nbsp;", "");
//							line = br.readLine();
//						}
//						br.readLine();
//						line = br.readLine();
//						courseInformation[5] = line.substring(line.indexOf(">")+1,line.indexOf("</a>")).trim().replaceAll("&nbsp;", "");
//						courseInfoLocatedFlag = true;
//					}
//					line = br.readLine();
//				}
//			}
//			if (line.contains("<td nowrap>Instructor:  </td>")) {
//				instructorInfoFoundFlag = true;
//				line = br.readLine();
//				line = line.substring(line.indexOf("<a href="));
//				this.instructor = line.substring(line.indexOf(">")+1,line.indexOf("</a>")).trim().replaceAll("&nbsp;", "");
//			}
			if (line.contains("Total Seats Remaining:")) {
				seatInfoFoundFlag = true;
				result = line.substring(line.indexOf("Total Seats Remaining:"));
				for (int i = 0; i < seatInformationArray.length; i++) {
					seatInformationArray[i] = Integer.parseInt(result
							.substring(result.indexOf("<b>") + 3,
									result.indexOf("</b>")));
					result = result.substring(result.indexOf("</b>") + 4);
				}
			}
			if (line.contains("<b>Book Summary</b>")) {
				bookInfoFoundFlag = true;
				if (line.contains("<b>ISBN &nbsp;&nbsp; </b></td></tr><tr>")) {

					String books = line.substring(line
							.indexOf("<td class='section"));
					while (books.contains("<td class='section")) {
						String title = "";
						String required = "";
						String author = "";
						String isbn = "";
						for (int i = 0; i < 4; i++) {
							String s = books.substring(
									books.indexOf("<td class='section") + 22,
									books.indexOf("</td>"));
						
							switch(i){
							case 0:
								title = s;
								break;
							case 1:
								required = s;
								break;
							case 2:
								author = s;
								break;
							case 3:
								isbn = s;
								break;
							}	
							books = books.substring(books.indexOf("</td>") + 5);
						}
						bookList.add(new BookInformation(title,required,author,isbn));
					}
				}
			}
			if (line.contains("Note: The remaining seats in this section are only available through a Standard Timetable (STT)")) {
				return 0;
			}
			if (seatInfoFoundFlag && bookInfoFoundFlag)
				return 1;
			line = br.readLine();
		}
		return -1;
	}

}
